package com.muqi.app.im.qmain;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMGroupChangeListener;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.TextMessageBody;
import com.easemob.easeui.R;
import com.easemob.easeui.controller.EaseUI;
import com.easemob.easeui.controller.EaseUI.EaseEmojiconInfoProvider;
import com.easemob.easeui.controller.EaseUI.EaseSettingsProvider;
import com.easemob.easeui.controller.EaseUI.EaseUserProfileProvider;
import com.easemob.easeui.domain.EaseEmojicon;
import com.easemob.easeui.domain.EaseEmojiconGroupEntity;
import com.easemob.easeui.domain.EaseUser;
import com.easemob.easeui.model.EaseNotifier;
import com.easemob.easeui.model.EaseNotifier.EaseNotificationInfoProvider;
import com.easemob.easeui.utils.EaseCommonUtils;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.muqi.app.im.db.EMDBManager;
import com.muqi.app.im.db.InviteMessgeDao;
import com.muqi.app.im.db.UserDao;
import com.muqi.app.im.domain.EmojiconExampleGroupData;
import com.muqi.app.im.domain.InviteMessage;
import com.muqi.app.im.domain.RobotUser;
import com.muqi.app.im.domain.InviteMessage.InviteMesageStatus;
import com.muqi.app.im.parse.UserProfileManager;
import com.muqi.app.im.receiver.CallReceiver;
import com.muqi.app.im.ui.ChatActivity;
import com.muqi.app.project.application.ActivitiesStack;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.utils.LogUtil;
import com.muqi.app.project.utils.NotificationHandler;
import com.muqi.app.project.utils.TimeMangerUtil;
import com.muqi.app.qlearn.fragments.BannerFragment;
import com.muqi.app.qlearn.login.LoginActivity;
import com.muqi.app.sharepreference.SharePreferenceUtil;
import com.muqi.app.user.db.CmdLoaclMessage;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;

public class EMHelper {
	/**
	 * 数据同步listener
	 */
	static public interface DataSyncListener {
		/**
		 * 同步完毕set
		 * 
		 * @param success
		 *            true：成功同步到数据，false失败
		 */
		public void onSyncComplete(boolean success);
	}

	protected static final String TAG = "DemoHelper";

	private EaseUI easeUI;

	/**
	 * EMEventListener
	 */
	protected EMEventListener eventListener = null;

	private Map<String, EaseUser> contactList;

	private Map<String, RobotUser> robotList;

	private UserProfileManager userProManager;

	private static EMHelper instance = null;

	private EmModel demoModel = null;

	/**
	 * HuanXin sync groups status listener
	 */
	private List<DataSyncListener> syncGroupsListeners;
	/**
	 * HuanXin sync contacts status listener
	 */
	private List<DataSyncListener> syncContactsListeners;
	/**
	 * HuanXin sync blacklist status listener
	 */
	private List<DataSyncListener> syncBlackListListeners;

	private boolean isSyncingGroupsWithServer = false;
	private boolean isSyncingContactsWithServer = false;
	private boolean isSyncingBlackListWithServer = false;
	private boolean isGroupsSyncedWithServer = false;
	private boolean isContactsSyncedWithServer = false;
	private boolean isBlackListSyncedWithServer = false;

	private boolean alreadyNotified = false;

	public boolean isVoiceCalling;
	public boolean isVideoCalling;

	private String username;

	private Context appContext;

	private CallReceiver callReceiver;

	private EMConnectionListener connectionListener;

	private InviteMessgeDao inviteMessgeDao;
	private UserDao userDao;

	private LocalBroadcastManager broadcastManager;

	private boolean isGroupAndContactListenerRegisted;

	private CupboardSQLiteOpenHelper dbHelper;
	private SQLiteDatabase sqlDb;
	private NotificationHandler nHandler;

	private SharePreferenceUtil mSpUtils;

	private EMHelper() {

	}

	public synchronized static EMHelper getInstance() {
		if (instance == null) {
			instance = new EMHelper();
		}
		return instance;
	}

	/**
	 * init helper
	 * 
	 * @param context
	 *            application context
	 */
	public void init(Context context) {
		if (EaseUI.getInstance().init(context)) {
			appContext = context;
			// 设为调试模式，打成正式包时，最好设为false，以免消耗额外的资源
			EMChat.getInstance().setDebugMode(false);
			// get easeui instance
			easeUI = EaseUI.getInstance();
			// 调用easeui的api设置providers
			setEaseUIProviders();
			demoModel = new EmModel(context);
			// 设置chat options
			setChatoptions();
			// 初始化PreferenceManager
			PreferenceManager.init(context);
			// 初始化用户管理类
			getUserProfileManager().init(context);

			// 设置全局监听
			setGlobalListeners();
			broadcastManager = LocalBroadcastManager.getInstance(appContext);
			initDbDao();

			dbHelper = new CupboardSQLiteOpenHelper(context);
			sqlDb = dbHelper.getWritableDatabase();
			nHandler = NotificationHandler.getInstance(context);

			mSpUtils = new SharePreferenceUtil(context, MContants.UserLogin);
			EMChatManager.getInstance().setMipushConfig("2882303761517465080",
					"5921746586080");
		}
	}

	private void setChatoptions() {
		// easeui库默认设置了一些options，可以覆盖
		EMChatOptions options = EMChatManager.getInstance().getChatOptions();
		options.allowChatroomOwnerLeave(getModel()
				.isChatroomOwnerLeaveAllowed());
		options.setDeleteMessagesAsExitGroup(true);

	}

	protected void setEaseUIProviders() {
		// 需要easeui库显示用户头像和昵称设置此provider
		easeUI.setUserProfileProvider(new EaseUserProfileProvider() {

			@Override
			public EaseUser getUser(String username) {
				return getUserInfo(username);
			}
		});

		// 不设置，则使用easeui默认的
		easeUI.setSettingsProvider(new EaseSettingsProvider() {

			@Override
			public boolean isSpeakerOpened() {
				return demoModel.getSettingMsgSpeaker();
			}

			@Override
			public boolean isMsgVibrateAllowed(EMMessage message) {
				return demoModel.getSettingMsgVibrate();
			}

			@Override
			public boolean isMsgSoundAllowed(EMMessage message) {
				return demoModel.getSettingMsgSound();
			}

			@Override
			public boolean isMsgNotifyAllowed(EMMessage message) {
				if (message == null) {
					return demoModel.getSettingMsgNotification();
				}
				if (!demoModel.getSettingMsgNotification()) {
					return false;
				} else {
					// 如果允许新消息提示
					// 屏蔽的用户和群组不提示用户
					String chatUsename = null;
					List<String> notNotifyIds = null;
					// 获取设置的不提示新消息的用户或者群组ids
					if (message.getChatType() == ChatType.Chat) {
						chatUsename = message.getFrom();
						notNotifyIds = demoModel.getDisabledIds();
					} else {
						chatUsename = message.getTo();
						notNotifyIds = demoModel.getDisabledGroups();
					}

					if (notNotifyIds == null
							|| !notNotifyIds.contains(chatUsename)) {
						return true;
					} else {
						return false;
					}
				}
			}
		});
		// 设置表情provider
		easeUI.setEmojiconInfoProvider(new EaseEmojiconInfoProvider() {

			@Override
			public EaseEmojicon getEmojiconInfo(String emojiconIdentityCode) {
				EaseEmojiconGroupEntity data = EmojiconExampleGroupData
						.getData();
				for (EaseEmojicon emojicon : data.getEmojiconList()) {
					if (emojicon.getIdentityCode().equals(emojiconIdentityCode)) {
						return emojicon;
					}
				}
				return null;
			}

			@Override
			public Map<String, Object> getTextEmojiconMapping() {
				// 返回文字表情emoji文本和图片(resource id或者本地路径)的映射map
				return null;
			}
		});

		// 不设置，则使用easeui默认的
		easeUI.getNotifier().setNotificationInfoProvider(
				new EaseNotificationInfoProvider() {

					@Override
					public String getTitle(EMMessage message) {
						// 修改标题,这里使用默认
						return null;
					}

					@Override
					public int getSmallIcon(EMMessage message) {
						// 设置小图标，这里为默认
						return 0;
					}

					@Override
					public String getDisplayedText(EMMessage message) {
						// 设置状态栏的消息提示，可以根据message的类型做相应提示
						String ticker = EaseCommonUtils.getMessageDigest(
								message, appContext);
						if (message.getType() == Type.TXT) {
							ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
						}
						EaseUser user = getUserInfo(message.getFrom());
						if (user != null) {
							return getUserInfo(message.getFrom()).getNick()
									+ ": " + ticker;
						} else {
							return message.getFrom() + ": " + ticker;
						}
					}

					@Override
					public String getLatestText(EMMessage message,
							int fromUsersNum, int messageNum) {
						return null;
						// return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
					}

					@Override
					public Intent getLaunchIntent(EMMessage message) {
						// 设置点击通知栏跳转事件
						Intent intent = new Intent(appContext,
								ChatActivity.class);
						// 有电话时优先跳转到通话页面
						if (isVideoCalling) {
							// intent = new Intent(appContext,
							// VideoCallActivity.class);
						} else if (isVoiceCalling) {
							// intent = new Intent(appContext,
							// VoiceCallActivity.class);
						} else {
							ChatType chatType = message.getChatType();
							if (chatType == ChatType.Chat) { // 单聊信息
								intent.putExtra("userId", message.getFrom());
								intent.putExtra("chatType",
										Constant.CHATTYPE_SINGLE);
							} else { // 群聊信息
								// message.getTo()为群聊id
								intent.putExtra("userId", message.getTo());
								if (chatType == ChatType.GroupChat) {
									intent.putExtra("chatType",
											Constant.CHATTYPE_GROUP);
								} else {
									intent.putExtra("chatType",
											Constant.CHATTYPE_CHATROOM);
								}
							}
						}
						return intent;
					}
				});
	}

	/**
	 * 设置全局事件监听
	 */
	protected void setGlobalListeners() {
		syncGroupsListeners = new ArrayList<DataSyncListener>();
		syncContactsListeners = new ArrayList<DataSyncListener>();
		syncBlackListListeners = new ArrayList<DataSyncListener>();

		isGroupsSyncedWithServer = demoModel.isGroupsSynced();
		isContactsSyncedWithServer = demoModel.isContactSynced();
		isBlackListSyncedWithServer = demoModel.isBacklistSynced();

		// create the global connection listener
		connectionListener = new EMConnectionListener() {
			@Override
			public void onDisconnected(int error) {
				if (error == EMError.USER_REMOVED) {
					onCurrentAccountRemoved();
				} else if (error == EMError.CONNECTION_CONFLICT) {
					onConnectionConflict();
				}
			}

			@Override
			public void onConnected() {
				// in case group and contact were already synced, we supposed to
				// notify sdk we are ready to receive the events
				if (isGroupsSyncedWithServer && isContactsSyncedWithServer) {
					new Thread() {
						@Override
						public void run() {
							EMHelper.getInstance().notifyForRecevingEvents();
						}
					}.start();
				} else {
					if (!isGroupsSyncedWithServer) {
						asyncFetchGroupsFromServer(null);
					}

					if (!isContactsSyncedWithServer) {
						asyncFetchContactsFromServer(null);
					}

					if (!isBlackListSyncedWithServer) {
						asyncFetchBlackListFromServer(null);
					}
				}
			}
		};

		IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance()
				.getIncomingCallBroadcastAction());
		if (callReceiver == null) {
			callReceiver = new CallReceiver();
		}

		// 注册通话广播接收者
		appContext.registerReceiver(callReceiver, callFilter);
		// 注册连接监听
		EMChatManager.getInstance().addConnectionListener(connectionListener);
		// 注册群组和联系人监听
		registerGroupAndContactListener();
		// 注册消息事件监听
		registerEventListener();
	}

	private void initDbDao() {
		inviteMessgeDao = new InviteMessgeDao(appContext);
		userDao = new UserDao(appContext);
	}

	/**
	 * 注册群组和联系人监听，由于logout的时候会被sdk清除掉，再次登录的时候需要再注册一下
	 */
	public void registerGroupAndContactListener() {
		if (!isGroupAndContactListenerRegisted) {
			// 注册群组变动监听
			EMGroupManager.getInstance().addGroupChangeListener(
					new MyGroupChangeListener());
			// 注册联系人变动监听
			EMContactManager.getInstance().setContactListener(
					new MyContactListener());
			isGroupAndContactListenerRegisted = true;
		}

	}

	/**
	 * 群组变动监听
	 */
	class MyGroupChangeListener implements EMGroupChangeListener {

		@Override
		public void onInvitationReceived(String groupId, String groupName,
				String inviter, String reason) {
			boolean hasGroup = false;
			for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
				if (group.getGroupId().equals(groupId)) {
					hasGroup = true;
					break;
				}
			}
			if (!hasGroup)
				return;
			// 被邀请
			String inviterMsg = "";
			EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
			msg.setChatType(ChatType.GroupChat);
			msg.setFrom(inviter);
			msg.setTo(groupId);
			msg.setMsgId(UUID.randomUUID().toString());
			msg.addBody(new TextMessageBody(inviterMsg));
			// 保存邀请消息
			EMChatManager.getInstance().saveMessage(msg);
			// 提醒新消息
			getNotifier().viberateAndPlayTone(msg);
			// 发送local广播
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_GROUP_CHANAGED));
		}

		@Override
		public void onInvitationAccpted(String groupId, String inviter,
				String reason) {

		}

		@Override
		public void onInvitationDeclined(String groupId, String invitee,
				String reason) {

		}

		@Override
		public void onUserRemoved(String groupId, String groupName) {
			// TODO 提示用户被T了，
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_GROUP_CHANAGED));
		}

		@Override
		public void onGroupDestroy(String groupId, String groupName) {
			// 群被解散
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_GROUP_CHANAGED));
		}

		@Override
		public void onApplicationReceived(String groupId, String groupName,
				String applyer, String reason) {
			// 用户申请加入群聊
			asyncInviteGroupMessage(applyer, groupId, groupName, reason);
		}

		@Override
		public void onApplicationAccept(String groupId, String groupName,
				String accepter) {
			String st4 ="";
			// 加群申请被同意
			EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
			msg.setChatType(ChatType.GroupChat);
			msg.setFrom(accepter);
			msg.setTo(groupId);
			msg.setMsgId(UUID.randomUUID().toString());
			msg.addBody(new TextMessageBody("俱乐部管理员  " + st4));
			// 保存同意消息
			EMChatManager.getInstance().saveMessage(msg);
			// 提醒新消息
			getNotifier().viberateAndPlayTone(msg);
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_GROUP_CHANAGED));
		}

		@Override
		public void onApplicationDeclined(String groupId, String groupName,
				String decliner, String reason) {
			// 加群申请被拒绝，demo未实现
		}
	}

	private void asyncInviteGroupMessage(final String applyer,
			final String groupId, final String groupName, final String reason) {
		new Thread(new Runnable() {
			public void run() {
				userProManager.asyncGetGroupInfo(groupId,
						new EMValueCallBack<EaseUser>() {

							@Override
							public void onSuccess(EaseUser stranger) {
								InviteMessage msg = new InviteMessage();
								msg.setFrom(applyer);
								msg.setFromAvatar(stranger.getAvatar());
								msg.setTime(System.currentTimeMillis());
								msg.setGroupId(groupId);
								msg.setGroupName(groupName);
								msg.setReason(reason);
								msg.setStatus(InviteMesageStatus.BEAPPLYED);
								notifyNewIviteMessage(msg);
								broadcastManager.sendBroadcast(new Intent(
										Constant.ACTION_GROUP_CHANAGED));
							}

							@Override
							public void onError(int arg0, String arg1) {

							}
						});
			}
		}).start();
	}

	/***
	 * 好友变化listener
	 * 
	 */
	public class MyContactListener implements EMContactListener {

		@Override
		public void onContactAdded(List<String> usernameList) {
			// 保存增加的联系人
			Map<String, EaseUser> localUsers = getContactList();
			final Map<String, EaseUser> toAddUsers = new HashMap<String, EaseUser>();
			for (String username : usernameList) {
				// 添加好友时可能会回调added方法两次
				if (!localUsers.containsKey(username)) {
					final String addName = username;
					getUserProfileManager().asyncGetUserInfo(username,
							new EMValueCallBack<EaseUser>() {

								@Override
								public void onSuccess(EaseUser adder) {
									userDao.saveContact(adder);
									toAddUsers.put(addName, adder);
								}

								@Override
								public void onError(int arg0, String arg1) {
									EaseUser user = new EaseUser(addName);
									userDao.saveContact(user);
									toAddUsers.put(addName, user);
								}
							});
				}
			}
			localUsers.putAll(toAddUsers);
			// 发送好友变动广播
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_CONTACT_CHANAGED));
		}

		@Override
		public void onContactDeleted(final List<String> usernameList) {
			// 被删除
			Map<String, EaseUser> localUsers = EMHelper.getInstance()
					.getContactList();
			for (String username : usernameList) {
				localUsers.remove(username);
				userDao.deleteContact(username);
				inviteMessgeDao.deleteMessage(username);
			}
			broadcastManager.sendBroadcast(new Intent(
					Constant.ACTION_CONTACT_CHANAGED));
		}

		@Override
		public void onContactInvited(String username, String reason) {
			// 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
			List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
			for (InviteMessage inviteMessage : msgs) {
				if (inviteMessage.getGroupId() == null
						&& inviteMessage.getFrom().equals(username)) {
					inviteMessgeDao.deleteMessage(username);
				}
			}
			asyncUserIviteMessage(username, "请求加你为好友", 1);
		}

		@Override
		public void onContactAgreed(String username) {
			List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
			for (InviteMessage inviteMessage : msgs) {
				if (inviteMessage.getFrom().equals(username)) {
					return;
				}
			}
			asyncUserIviteMessage(username, "", 2);
		}

		@Override
		public void onContactRefused(String username) {
			// 参考同意，被邀请实现此功能
			Log.d(username, username + "拒绝了你的好友请求");
		}
	}

	private void asyncUserIviteMessage(final String userName,
			final String reason, final int msgType) {
		new Thread(new Runnable() {
			public void run() {
				userProManager.asyncGetUserInfo(userName,
						new EMValueCallBack<EaseUser>() {

							@Override
							public void onSuccess(EaseUser stranger) {
								// 自己封装的javabean
								InviteMessage msg = new InviteMessage();
								msg.setFrom(userName);
								msg.setTime(System.currentTimeMillis());
								msg.setReason(reason);
								msg.setFromNick(stranger.getNick());
								msg.setFromAvatar(stranger.getAvatar());
								// 设置相应status
								if (msgType == 1) {
									msg.setStatus(InviteMesageStatus.BEINVITEED);
								} else {
									msg.setStatus(InviteMesageStatus.BEAGREED);
								}
								notifyNewIviteMessage(msg);
							}

							@Override
							public void onError(int arg0, String arg1) {

							}
						});
			}
		}).start();
	}

	/**
	 * 保存并提示消息的邀请消息
	 * 
	 * @param msg
	 */
	private void notifyNewIviteMessage(InviteMessage msg) {
		if (inviteMessgeDao == null) {
			inviteMessgeDao = new InviteMessgeDao(appContext);
		}
		inviteMessgeDao.saveMessage(msg);
		// 保存未读数，这里没有精确计算
		inviteMessgeDao.saveUnreadMessageCount(1);
		// 提示有新消息
		getNotifier().viberateAndPlayTone(null);

		broadcastManager.sendBroadcast(new Intent(
				Constant.ACTION_CONTACT_CHANAGED));
	}

	/**
	 * 账号在别的设备登录
	 */
	protected void onConnectionConflict() {
		Intent intent = new Intent(appContext, LoginActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra(Constant.ACCOUNT_CONFLICT, true);
		ActivitiesStack.getInstance().popAll(true);
		appContext.startActivity(intent);

	}

	/**
	 * 账号被移除
	 */
	protected void onCurrentAccountRemoved() {
		Intent intent = new Intent(appContext, LoginActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra(Constant.ACCOUNT_REMOVED, true);
		ActivitiesStack.getInstance().popAll(true);
		appContext.startActivity(intent);

	}

	private EaseUser getUserInfo(final String username) {
		// 获取user信息，demo是从内存的好友列表里获取，
		// 实际开发中，可能还需要从服务器获取用户信息,
		// 从服务器获取的数据，最好缓存起来，避免频繁的网络请求
		EaseUser user = null;
		if (username.equals(EMChatManager.getInstance().getCurrentUser()))
			return getUserProfileManager().getCurrentUserInfo();
		user = getContactList().get(username);
		// TODO 获取不在好友列表里的群成员具体信息，即陌生人信息,维护在robot表里
		if (user == null && getRobotList() != null) {
			user = getRobotList().get(username);
		}
		// TODO 异步更新陌生人信息,维护在robot表里
		if (user == null) {
			asyncStrangerInfo(username);
		}
		return user;
	}

	/**
	 * 异步获取陌生联系人信息
	 * 
	 * @param strangerName
	 */
	private void asyncStrangerInfo(final String strangerName) {
		new Thread(new Runnable() {
			public void run() {
				userProManager.asyncGetUserInfo(strangerName,
						new EMValueCallBack<EaseUser>() {

							@Override
							public void onSuccess(EaseUser stranger) {
								if (robotList == null)
									robotList = new HashMap<String, RobotUser>();
								RobotUser robot = new RobotUser(strangerName);
								robot.setAvatar(stranger.getAvatar());
								robot.setNick(stranger.getNick());
								robotList.put(strangerName, robot);
								setRobotList(robotList);
								saveStangerList(robot);
							}

							@Override
							public void onError(int arg0, String arg1) {

							}
						});
			}
		}).start();
	}

	/**
	 * 异步获取群头像信息
	 * 
	 * @param strangerName
	 */
	private void asyncGroupInfo(final String groupName) {
		new Thread(new Runnable() {
			public void run() {
				userProManager.asyncGetGroupInfo(groupName,
						new EMValueCallBack<EaseUser>() {

							@Override
							public void onSuccess(EaseUser stranger) {
								if (robotList == null)
									robotList = new HashMap<String, RobotUser>();
								RobotUser robot = new RobotUser(groupName);
								robot.setAvatar(stranger.getAvatar());
								robot.setNick(stranger.getNick());
								robotList.put(groupName, robot);
								setRobotList(robotList);
								saveStangerList(robot);
							}

							@Override
							public void onError(int arg0, String arg1) {

							}
						});
			}
		}).start();
	}

	/**
	 * 全局事件监听 因为可能会有UI页面先处理到这个消息，所以一般如果UI页面已经处理，这里就不需要再次处理 activityList.size()
	 * <= 0 意味着所有页面都已经在后台运行，或者已经离开Activity Stack
	 */
	protected void registerEventListener() {
		eventListener = new EMEventListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onEvent(EMNotifierEvent event) {
				EMMessage message = null;
				if (event.getData() instanceof EMMessage) {
					message = (EMMessage) event.getData();
				}
				switch (event.getEvent()) {
				case EventNewMessage:
					// 应用在后台，不需要刷新UI,通知栏提示新消息
					if (!easeUI.hasForegroundActivies()) {
						getNotifier().onNewMsg(message);
					}
					break;
				case EventOfflineMessage:
					if (!easeUI.hasForegroundActivies()) {
						EMLog.d(TAG, "received offline messages");
						List<EMMessage> messages = (List<EMMessage>) event
								.getData();
						getNotifier().onNewMesg(messages);
					}
					break;
				case EventNewCMDMessage:
					// 获取消息body
					CmdMessageBody cmdMsgBody = (CmdMessageBody) message
							.getBody();
					final String action = cmdMsgBody.action;// 获取自定义action
					LogUtil.e("CMD推送：" + cmdMsgBody);
					setCmdMessage(action, message);

					break;
				case EventDeliveryAck:
					message.setDelivered(true);
					break;
				case EventReadAck:
					message.setAcked(true);
					break;
				default:
					break;
				}
			}
		};
		EMChatManager.getInstance().registerEventListener(eventListener);
	}

	private void setCmdMessage(final String action, EMMessage msgContent) {
		if (action == null || TextUtils.isEmpty(action)) {
			return;
		}
		try {
			int count = 0;
			CmdLoaclMessage localmsg = new CmdLoaclMessage();
			if ("evaluate".equals(action)) {
				localmsg.msg_type = msgContent.getStringAttribute("obj_type");
				localmsg.content = msgContent.getStringAttribute("msg");
				localmsg.titile = "课堂评价";
				localmsg.type = 3;
				localmsg.action = action;
				localmsg.msg_type = action;
				localmsg.time = TimeMangerUtil.getSystemTime();
				count = mSpUtils.getNotification(mSpUtils.getCurrentChildId()
						+ "c") + 1;
				mSpUtils.setNotification(mSpUtils.getCurrentChildId() + "c",
						count);
				appContext.sendBroadcast(new Intent(
						BannerFragment.BANNER_COMMENT_CHANGED));

			}else if("broadcast".equals(action)){
				localmsg.msg_id = msgContent.getStringAttribute("id");
				localmsg.content = "试题回复";
				localmsg.titile = "试题回复";
				localmsg.type = 4;
				localmsg.action = action;
				localmsg.msg_type = action;
				localmsg.time = TimeMangerUtil.getSystemTime();
				count = mSpUtils.getNotification(mSpUtils.getCurrentChildId()
						+ "c") + 1;
				mSpUtils.setNotification(mSpUtils.getCurrentChildId() + "e",
						count);
				appContext.sendBroadcast(new Intent(
						BannerFragment.BANNER_EXAMINATION_CHANGED));
			} else {
				String msg = msgContent.getStringAttribute("content");
				localmsg.host_user_id = getCurrentUsernName();
				localmsg.from_user_id = msgContent
						.getStringAttribute("from_user_id");
				localmsg.msg_id = msgContent.getStringAttribute("obj_id");
				localmsg.msg_type = msgContent.getStringAttribute("obj_type");

				localmsg.action = action;
				// localmsg.titile = msgContent.getStringAttribute("title");
				localmsg.content = msg;
				localmsg.time = TimeMangerUtil.getSystemTime();

				localmsg.quantity = msgContent.getStringAttribute("quantity");
				localmsg.money = msgContent.getStringAttribute("money");
				localmsg.isCkeck = false;
				if (localmsg.msg_type.equals("class_job")) {
					localmsg.type = 1;
					localmsg.titile = "作业";
					count = mSpUtils.getNotification(mSpUtils
							.getCurrentChildId() + "h") + 1;
					mSpUtils.setNotification(
							mSpUtils.getCurrentChildId() + "h", count);
					appContext.sendBroadcast(new Intent(
							BannerFragment.BANNER_HOME_CHANGED));
				} else {
					localmsg.type = 2;
					localmsg.titile = "通知";
					count = mSpUtils.getNotification(mSpUtils.getCurrentChildId()
							+ "n") + 1;
					mSpUtils.setNotification(mSpUtils.getCurrentChildId() + "n",
							count);
					appContext.sendBroadcast(new Intent(
							BannerFragment.BANNER_HOME_CHANGED));
				}

			}
			localmsg.user_id = mSpUtils.getUserId();
			cupboard().withDatabase(sqlDb).put(localmsg);
			// nHandler.createSimpleMsgNotify(appContext, localmsg.titile, msg,
			// localmsg.msg_type);
			if (demoModel.getSettingMsgNotification()) {
				nHandler.createSimpleMsgNotify(appContext, localmsg.titile,
						localmsg.content, localmsg.msg_type);
			}
		} catch (EaseMobException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 是否登录成功过
	 * 
	 * @return
	 */
	public boolean isLoggedIn() {
		return EMChat.getInstance().isLoggedIn();
	}

	/**
	 * 退出登录
	 * 
	 * @param unbindDeviceToken
	 *            是否解绑设备token(使用GCM才有)
	 * @param callback
	 *            callback
	 */
	public void logout(boolean unbindDeviceToken, final EMCallBack callback) {
		endCall();
		EMChatManager.getInstance().logout(unbindDeviceToken, new EMCallBack() {

			@Override
			public void onSuccess() {
				reset();
				if (callback != null) {
					callback.onSuccess();
				}
			}

			@Override
			public void onProgress(int progress, String status) {
				if (callback != null) {
					callback.onProgress(progress, status);
				}
			}

			@Override
			public void onError(int code, String error) {
				if (callback != null) {
					callback.onError(code, error);
				}
			}
		});
	}

	/**
	 * 获取消息通知类
	 * 
	 * @return
	 */
	public EaseNotifier getNotifier() {
		return easeUI.getNotifier();
	}

	public EmModel getModel() {
		return (EmModel) demoModel;
	}

	/**
	 * 设置好友user list到内存中
	 * 
	 * @param contactList
	 */
	public void setContactList(Map<String, EaseUser> contactList) {
		this.contactList = contactList;
	}

	/**
	 * 保存单个user
	 */
	public void saveContact(EaseUser user) {
		contactList.put(user.getUsername(), user);
		demoModel.saveContact(user);
	}

	/**
	 * 获取好友list
	 * 
	 * @return
	 */
	public Map<String, EaseUser> getContactList() {
		if (isLoggedIn() && contactList == null) {
			contactList = demoModel.getContactList();
		}
		return contactList;
	}

	/**
	 * 设置当前用户的环信id
	 * 
	 * @param username
	 */
	public void setCurrentUserName(String username) {
		this.username = username;
		demoModel.setCurrentUserName(username);
	}

	/**
	 * 获取当前用户的环信id
	 */
	public String getCurrentUsernName() {
		if (username == null) {
			username = demoModel.getCurrentUsernName();
		}
		return username;
	}

	public void setRobotList(Map<String, RobotUser> robotList) {
		this.robotList = robotList;
	}

	public void saveStangerList(RobotUser stanger) {
		List<RobotUser> stangerList = new ArrayList<RobotUser>();
		stangerList.add(stanger);
		demoModel.saveRobotList(stangerList);
	}

	public Map<String, RobotUser> getRobotList() {
		if (isLoggedIn() && robotList == null) {
			robotList = demoModel.getRobotList();
		}
		return robotList;
	}

	/**
	 * update user list to cach And db
	 * 
	 * @param contactList
	 */
	public void updateContactList(List<EaseUser> contactInfoList) {
		for (EaseUser u : contactInfoList) {
			contactList.put(u.getUsername(), u);
		}
		ArrayList<EaseUser> mList = new ArrayList<EaseUser>();
		mList.addAll(contactList.values());
		demoModel.saveContactList(mList);
	}

	public UserProfileManager getUserProfileManager() {
		if (userProManager == null) {
			userProManager = new UserProfileManager();
		}
		return userProManager;
	}

	void endCall() {
		try {
			EMChatManager.getInstance().endCall();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addSyncGroupListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (!syncGroupsListeners.contains(listener)) {
			syncGroupsListeners.add(listener);
		}
	}

	public void removeSyncGroupListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (syncGroupsListeners.contains(listener)) {
			syncGroupsListeners.remove(listener);
		}
	}

	public void addSyncContactListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (!syncContactsListeners.contains(listener)) {
			syncContactsListeners.add(listener);
		}
	}

	public void removeSyncContactListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (syncContactsListeners.contains(listener)) {
			syncContactsListeners.remove(listener);
		}
	}

	public void addSyncBlackListListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (!syncBlackListListeners.contains(listener)) {
			syncBlackListListeners.add(listener);
		}
	}

	public void removeSyncBlackListListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (syncBlackListListeners.contains(listener)) {
			syncBlackListListeners.remove(listener);
		}
	}

	/**
	 * 同步操作，从服务器获取群组列表 该方法会记录更新状态，可以通过isSyncingGroupsFromServer获取是否正在更新
	 * 和isGroupsSyncedWithServer获取是否更新已经完成
	 * 
	 * @throws EaseMobException
	 */
	public synchronized void asyncFetchGroupsFromServer(
			final EMCallBack callback) {
		if (isSyncingGroupsWithServer) {
			return;
		}
		isSyncingGroupsWithServer = true;

		new Thread() {
			@Override
			public void run() {
				try {
					EMGroupManager.getInstance().getGroupsFromServer();
					// in case that logout already before server returns, we
					// should return immediately
					if (!EMChat.getInstance().isLoggedIn()) {
						return;
					}
					demoModel.setGroupsSynced(true);
					isGroupsSyncedWithServer = true;
					isSyncingGroupsWithServer = false;
					// 通知listener同步群组完毕
					noitifyGroupSyncListeners(true);
					if (isContactsSyncedWithServer()) {
						notifyForRecevingEvents();
					}
					if (callback != null) {
						callback.onSuccess();
					}
				} catch (EaseMobException e) {
					demoModel.setGroupsSynced(false);
					isGroupsSyncedWithServer = false;
					isSyncingGroupsWithServer = false;
					noitifyGroupSyncListeners(false);
					if (callback != null) {
						callback.onError(e.getErrorCode(), e.toString());
					}
				}
			}
		}.start();
	}

	public void noitifyGroupSyncListeners(boolean success) {
		for (DataSyncListener listener : syncGroupsListeners) {
			listener.onSyncComplete(success);
		}
	}

	public void asyncFetchContactsFromServer(
			final EMValueCallBack<List<String>> callback) {
		if (isSyncingContactsWithServer) {
			return;
		}
		isSyncingContactsWithServer = true;
		new Thread() {
			@Override
			public void run() {
				List<String> usernames = null;
				try {
					usernames = EMContactManager.getInstance()
							.getContactUserNames();
					// in case that logout already before server returns, we
					// should return immediately
					if (!EMChat.getInstance().isLoggedIn()) {
						return;
					}
					Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
					for (String username : usernames) {
						EaseUser user = new EaseUser(username);
						EaseCommonUtils.setUserInitialLetter(user);
						userlist.put(username, user);
					}
					// 存入内存
					getContactList().clear();
					getContactList().putAll(userlist);
					// 存入db
					UserDao dao = new UserDao(appContext);
					List<EaseUser> users = new ArrayList<EaseUser>(
							userlist.values());
					dao.saveContactList(users);

					demoModel.setContactSynced(true);
					isContactsSyncedWithServer = true;
					isSyncingContactsWithServer = false;

					// 通知listeners联系人同步完毕
					notifyContactsSyncListener(true);
					if (isGroupsSyncedWithServer()) {
						notifyForRecevingEvents();
					}
					getUserProfileManager().asyncFetchContactInfosFromServer(
							usernames, new EMValueCallBack<List<EaseUser>>() {

								@Override
								public void onSuccess(List<EaseUser> uList) {
									updateContactList(uList);
									getUserProfileManager()
											.notifyContactInfosSyncListener(
													true);
								}

								@Override
								public void onError(int error, String errorMsg) {

								}
							});
					if (callback != null) {
						callback.onSuccess(usernames);
					}
				} catch (EaseMobException e) {
					demoModel.setContactSynced(false);
					isContactsSyncedWithServer = false;
					isSyncingContactsWithServer = false;
					noitifyGroupSyncListeners(false);
					e.printStackTrace();
					if (callback != null) {
						callback.onError(e.getErrorCode(), e.toString());
					}
				}
			}
		}.start();
	}

	public void notifyContactsSyncListener(boolean success) {
		for (DataSyncListener listener : syncContactsListeners) {
			listener.onSyncComplete(success);
		}
	}

	public void asyncFetchBlackListFromServer(
			final EMValueCallBack<List<String>> callback) {

		if (isSyncingBlackListWithServer) {
			return;
		}

		isSyncingBlackListWithServer = true;

		new Thread() {
			@Override
			public void run() {
				try {
					List<String> usernames = EMContactManager.getInstance()
							.getBlackListUsernamesFromServer();

					// in case that logout already before server returns, we
					// should return immediately
					if (!EMChat.getInstance().isLoggedIn()) {
						return;
					}
					demoModel.setBlacklistSynced(true);
					isBlackListSyncedWithServer = true;
					isSyncingBlackListWithServer = false;

					EMContactManager.getInstance().saveBlackList(usernames);
					notifyBlackListSyncListener(true);
					if (callback != null) {
						callback.onSuccess(usernames);
					}
				} catch (EaseMobException e) {
					demoModel.setBlacklistSynced(false);

					isBlackListSyncedWithServer = false;
					isSyncingBlackListWithServer = true;
					e.printStackTrace();

					if (callback != null) {
						callback.onError(e.getErrorCode(), e.toString());
					}
				}
			}
		}.start();
	}

	public void notifyBlackListSyncListener(boolean success) {
		for (DataSyncListener listener : syncBlackListListeners) {
			listener.onSyncComplete(success);
		}
	}

	public boolean isSyncingGroupsWithServer() {
		return isSyncingGroupsWithServer;
	}

	public boolean isSyncingContactsWithServer() {
		return isSyncingContactsWithServer;
	}

	public boolean isSyncingBlackListWithServer() {
		return isSyncingBlackListWithServer;
	}

	public boolean isGroupsSyncedWithServer() {
		return isGroupsSyncedWithServer;
	}

	public boolean isContactsSyncedWithServer() {
		return isContactsSyncedWithServer;
	}

	public boolean isBlackListSyncedWithServer() {
		return isBlackListSyncedWithServer;
	}

	public synchronized void notifyForRecevingEvents() {
		if (alreadyNotified) {
			return;
		}
		// 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
		EMChat.getInstance().setAppInited();
		alreadyNotified = true;
	}

	synchronized void reset() {
		isSyncingGroupsWithServer = false;
		isSyncingContactsWithServer = false;
		isSyncingBlackListWithServer = false;

		demoModel.setGroupsSynced(false);
		demoModel.setContactSynced(false);
		demoModel.setBlacklistSynced(false);

		isGroupsSyncedWithServer = false;
		isContactsSyncedWithServer = false;
		isBlackListSyncedWithServer = false;

		alreadyNotified = false;
		isGroupAndContactListenerRegisted = false;

		setContactList(null);
		setRobotList(null);
		getUserProfileManager().reset();
		EMDBManager.getInstance().closeDB();
	}

	public void pushActivity(Activity activity) {
		easeUI.pushActivity(activity);
	}

	public void popActivity(Activity activity) {
		easeUI.popActivity(activity);
	}

}
